import 'dart:math';

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_member/utils/calls_and_messages_service.dart';
import 'package:flutter_member/utils/math_distance.dart';
import 'package:flutter_member/utils/service_locator.dart';
import 'package:flutter_member/widget/bottm_sheet_dialog.dart';
import 'package:flutter_member/widget/distance_widget.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_member/widget/search_records.dart';
import 'package:flutter_member/widget/search_width.dart';
import 'package:flutter_member/widget/universal_card.dart';
import 'package:flutter_member/widget/universal_card_item.dart';
// import 'package:maps_launcher/maps_launcher.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:toast/toast.dart';

///分校网络入口
///
class IndexSchoolNetWork extends StatefulWidget {
  @override
  _IndexSchoolNetWorkState createState() => _IndexSchoolNetWorkState();
}

class _IndexSchoolNetWorkState extends State<IndexSchoolNetWork> {


  /// 拨打电话
  final CallsAndMessagesService _service = locator<CallsAndMessagesService>();

  //搜索
  List<String> searchList = ['儒林教育集團有限公司'];

  //推薦
  List<String> recentSuggest = ['儒林教育集團有限公司', '敦仁補習/教育中心', '儒林補習/教育中心10'];
  bool isDrawer = false;
  var _indexedStack = 0;
  var _focusView = false;
  var deleteFocus = false;

  /// 位置
  Location _location;
  String _fenceStatus;

  // 一次加载5条数据
  int loadData = 5;

  // 加载中
  bool _loading = true;

  // 搜索中
  bool _searchLoading = false;

  // 搜索记录
  List<dynamic> listBranchSearch = [];

  var _search;

  var _searchEditing = new TextEditingController();
  FocusNode _focusNode = FocusNode();

  /// 存储分支信息
  List<dynamic> _listBranch = [];

  /// 存储搜索的学校信息
  List<dynamic> listBranch = [];

  // tab OR listView
  String type = "tab";

  /// 經緯度
  ParseGeoPoint point = new ParseGeoPoint();

  /// 獲得分支
  Future<void> _getBranchLayers() async {
    var query = QueryBuilder(ParseObject("BranchLayer"))
      ..whereMatchesQuery(
          "parent",
          QueryBuilder(ParseObject("BranchLayer"))
            ..whereEqualTo("code", "external"))
      ..includeObject(["branches", "branches.contacts"]);
    var rep = await query.query();
    if (rep.success && rep.results != null) {
      _loading = false;

      setState(() => _listBranch = rep.results
          .map((e) => {e["displayName"]: e["branches"]})
          .toList(growable: false));
    } else {
      setState(() => _loading = false);
    }
  }

  /// 搜索门店
  ///
  Future<void> _searchBranch({String displayName}) async {
    setState(() => _searchLoading = true);
    var query = QueryBuilder(ParseObject("BranchLayer"))
      ..whereMatchesQuery(
          "parent",
          QueryBuilder(ParseObject("BranchLayer"))
            ..whereEqualTo("code", "external"))
      ..includeObject(["branches"]);
    var rep = await query.query();
    if (rep.success && rep.results != null) {
      rep.results.map((e) async {
        QueryBuilder query2;
        List<QueryBuilder<ParseObject>> list = [];
        e["branches"].map((bran) {
          list.add(QueryBuilder(ParseObject("Branch"))
            ..whereStartsWith("displayName", displayName)
            ..whereEqualTo("objectId", bran["objectId"]));
        }).toList();
        query2 = QueryBuilder.or(ParseObject("Branch"), list);
        var repBranch = await query2.query();
        if (repBranch.results != null && repBranch.success) {
          setState(() => listBranch = repBranch.results.map((e) => e).toList());
          setState(() => type = "list");
          setState(() => _searchLoading = false);
          FocusScope.of(context).requestFocus(FocusNode());
        } else {
          setState(() => _searchLoading = false);
          setState(()=>listBranch.clear());
          FocusScope.of(context).requestFocus(FocusNode());
        }
      }).toList();
    }
  }

  @override
  void initState() {
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          _focusView = true;
        });
      } else {
        setState(() {
          _focusView = false;
          //焦點被取消時進行搜索
          if (!deleteFocus) {
            _searchBranch(displayName: _searchEditing.text);
          }
        });
      }
    });
    super.initState();
    _getLocation();
    _getBranchLayers();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    TabController _tabController;
    return DefaultTabController(
      length: _listBranch.length,
      child: Scaffold(
        body: Container(
          child: Column(
            children: <Widget>[
              // 自定義頂部搜索組件
              SearchWidth(
                src: 'images/top_school_network.png',
                inputController: _searchEditing,
                focusNode: _focusNode,
                hintText: '搜尋門店',
                downColor: Color(0XffC2DBF0),
                upColor: Color(0Xff154471),
                onChange: (v) {
                  setState(() {
                    _search = v;
                  });
                },
                onPressed: () => setState(() {
                  _searchBranch(displayName: _searchEditing.text);
                }),
              ),
              Expanded(
                  child: Stack(
                    children: [
                      WillPopScope(
                          child: _body(_tabController),
                          onWillPop: () {
                            setState(() {
                              if (type == "list") {
                                setState(() => type = "tab");
                              }
                            });
                            return null;
                          }),
                      _searchRecode()
                    ],
                  ))
            ],
          ),
        ),
        resizeToAvoidBottomPadding: false,
      ),
    );
  }

  /// 内容区域
  Widget _body(TabController _tabController) {
    if (_loading == true) {
      return CLoadingDialog(
        text: "加載中",
      );
    } else if (type == "list") {
      return Container(
        child: EasyRefresh(
          header: PhoenixHeader(),
          footer: PhoenixFooter(),
          child: SingleChildScrollView(
            child: _searchLoading == true
                ? CLoadingDialog(
              text: "搜索中",
            )
                : listBranch.length==0?NoDataWidget():Column(
              children: listBranch
                  .map((e) => UniversalCard(
                onPressed: () => Application.jump(context,
                    "/page/campusNetwork_detailsPage/${e["objectId"]}"),
                title: e["displayName"],
                children: [
                  UniversalCardItem(
                      icon: "images/address.png",
                      title: e["address"]),
                  UniversalCardItem(
                      icon: "images/course_phone.png",
                      title: e["address"]),
                ],
              ))
                  .toList(),
            ),
          ),
        ),
      );
    } else if (_listBranch.length != 0) {
      return Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              new Expanded(
                flex: 8,
                child: TabBar(
                  isScrollable: true,
                  indicatorColor: Colors.yellow,
                  //指示器颜色
                  indicatorWeight: 5,
                  //指示器高度
                  indicatorPadding: EdgeInsets.fromLTRB(35, 0, 35, 0),
                  //底部指示器的Padding
                  labelColor: Color(0xff3d6fc1),
                  //选中label颜色
                  unselectedLabelColor: Color(0xffd9d9d9),
                  //未选中label颜色
                  labelStyle:
                  TextStyle(fontWeight: FontWeight.w800, fontSize: 18),
                  tabs: listTabTitle(),
                  controller: _tabController,
                ),
              )
            ],
          ),
          Expanded(
              child: TabBarView(
                children: listContent(),
              ))
        ],
      );
    } else {
      return NoDataWidget();
    }
  }

  //// 搜索记录
  Widget _searchRecode() {
    if (_focusView) {
      return SearchRecords(
        searchRecords: searchList,
        searchHot: recentSuggest,
        clear: () {
          deleteFocus = true;
          _deleteSearch();
        },
        onClick: (str) {
          _search = str;
          _searchEditing.text = str;
          _searchBranch(displayName: _searchEditing.text);
        },
      );
    } else {
      return Container();
    }
  }

  /*-------------tab切换item和内容主要部分start---------------*/

  /// tab標籤
  List<Widget> listTabTitle() {
    List<Widget> listWidget = [];
    print(_listBranch);
    _listBranch.map((e) {
      e.forEach((k, v) {
        listWidget.add(Tab(
          text: k,
        ));
      });
    }).toList();
    return listWidget;
  }

  /// 内容
  List<Widget> listContent({String displayName}) {
    List<Widget> listWidget = [];
    _listBranch.map((e) {
      e.forEach((k, v) {
        listWidget.add(EasyRefresh(
          header: PhoenixHeader(),
          footer: PhoenixFooter(),
          onRefresh: _getBranchLayers,
          child: SingleChildScrollView(
            child: Column(
              children: listContentItem(data: v),
            ),
          ),
        ));
      });
    }).toList();
    return listWidget;
  }

  /// 内容Item
  List<Widget> listContentItem({List data}) {
    List<Widget> list = [];
    data.map((e) {
      setState(() => point = e['location']);
      list.add(UniversalCard(
        onPressed: () => Application.jump(
            context, "/page/campusNetwork_detailsPage/${e["objectId"]}"),
        title: e["displayName"],
        children: [
          UniversalCardItem(
              icon: "images/address.png",
              title: e["address"],
              onPress: () {
                List list = ["高德地圖", '谷歌地圖'];
                showPayActionSheets(
                    title: "選擇地圖", type: "maps", data: list, context: context);
              }),
          UniversalCardItem(
              icon: "images/course_phone.png",
              title: e["contacts"]
                  .map((p) {
                if (p["type"] != "email" && p["value"] != null) {
                  return p["value"] + "/";
                }
              })
                  .toList()
                  .toString(),
              onPress: () {
                List list = [];
                e["contacts"].map((p) {
                  if (p["type"] != "email" && p["value"] != null) {
                    list.add(p["value"]);
                  }
                }).toList();
                showPayActionSheets(
                    title: "撥打電話", type: "tel", data: list, context: context);
              }),
          DistanceWidget(
            distance: _location != null
                ? MathDistance.getDistance(_location.latLng.longitude,
                _location.latLng.latitude, point.longitude, point.latitude)
                : 0,
          )
        ],
      ));
    }).toList();
    return list;
  }

  /*-------------tab切换item和内容主要部分end---------------*/

  /*-------------底部弹窗START------------------*/

  /// 具体使用方式
  Future<int> showPayActionSheets(
      {@required BuildContext context,
        @required String title,
        @required List data,
        @required String type}) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        children: data
            .map((e) => actionItem(
            context: context,
            index: 1,
            title: e,
            onTop: () {
              if (type == "maps") {
                // MapsLauncher.launchCoordinates(point.latitude,
                //     point.longitude, 'Google Headquarters are here');
              } else {
                print(e);
                _service.call(e);
                Navigator.pop(context);
              }
            }))
            .toList());
  }

  /*-------------底部弹窗END------------------*/

  /*-------------高德地圖定位start ----------------*/

  /// 获得当前经纬度
  Future<void> _getLocation() async {
    if (await requestPermission()) {
      final location = await AmapLocation.instance.fetchLocation();
      setState(() => _location = location);
    }
  }

  /// 計算兩個經緯度的距離
  /// 根据两点经纬度 使用math 算出之间距离
  /// 导入import 'dart:math';

  /*-------------高德地圖定位end ----------------*/
  //刪除搜索紀錄
  void _deleteSearch() {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.all(10),
            height: 200,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                    width: MediaQuery.of(context).size.width - 20,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Color(0Xffececec),
                      borderRadius: BorderRadius.circular(15.0), //邊框
                    ),
                    child: Center(
                      child: Text(
                        '是否要清空搜索紀錄?',
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                        ),
                      ),
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      searchList.clear();
                      Navigator.of(context).pop();
                      //_focusView = false;
                    });
                  },
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery.of(context).size.width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '確 認',
                          style: TextStyle(
                            color: Color(0Xff4d80c5),
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                ),
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery.of(context).size.width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '取 消',
                          style: TextStyle(
                            color: Colors.red,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                )
              ],
            ),
          );
        });
  }

  Future<bool> requestPermission() async {
    final permissions = await Permission.locationWhenInUse.request();

    if (permissions.isGranted) {
      return true;
    } else {
      Toast.show("需要定位权限", context);
      return false;
    }
  }
}